package com.jumi.microservice.controller.api;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jm.member.common.core.utils.LocalDateTimeUtil;
import com.jm.member.common.core.utils.ServletUtils;
import com.jm.member.common.jwt.constant.JwtAdminInfo;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.controller.JmUserFenxiaoController;
import com.jumi.microservice.dto.reponse.api.FenXiaoAggregate;
import com.jumi.microservice.dto.reponse.api.FenXiaoItem;
import com.jumi.microservice.dto.reponse.api.SelfShopResponse;
import com.jumi.microservice.entity.*;
import com.jumi.microservice.enums.CommonEnum;
import com.jumi.microservice.enums.FenXiaoStatus;
import com.jumi.microservice.enums.FenXiaoType;
import com.jumi.microservice.enums.SalesStatus;
import com.jumi.microservice.service.*;
import com.jumi.microservice.util.WrapperUtil;
import io.swagger.annotations.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


@RequestMapping("/api/fenxiao")
@RestController
@Api(tags = "C-收益")
public class FenXiaoController {

    @Autowired
    IJmUserFenxiaoService fenxiaoService;

    @Autowired
    JmUserFenxiaoController controller;

    @Autowired
    IJmUserService userService;

    @Autowired
    IJmUserSalesService salesService;

    @Autowired
    IJmUserInviteService inviteService;

    @Autowired
    IJmUserFenxiaoHistoryService fenxiaoHistoryService;

    @Resource
    IJmUserStatisticsFenxiaoService statisticsFenxiaoService;

    @Resource
    IJmUserStatisticsSalesService statisticsSalesService;

    @Resource
    IJmUserStatisticsTeamService statisticsTeamService;


    @Resource
    IJmUserTeamService userTeamService;

    @DubboReference(check = false)
    IWalletInOrOutService iWalletInOrOutService;


    @GetMapping("/getAll")
    @ApiOperation(value = "用户总收益", tags = "用户总收益", response = FenXiaoAggregate.class)
    public ResponseResult getAll() {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
//        Integer memberId = 460;
        JmUser jmUser = userService.checkUserExist(memberId);//用户信息

        JmUserFenxiao fenxiao = new JmUserFenxiao();//用来构建查询条件,查询用户总收益
        fenxiao.setUid(memberId);
        fenxiao.setIsDel(CommonEnum.否);
        QueryWrapper fxWrapper = WrapperUtil.getWrapper(null, fenxiao);
        fxWrapper.ne("status", FenXiaoStatus.失效);
        BigDecimal sumYongJin = fenxiaoService.getSumYongJin(fxWrapper);//总收益


        //修改查询条件状态为 未结算,查询未结算的数据;
        fenxiao.setStatus(FenXiaoStatus.未结算);
        fxWrapper = WrapperUtil.getWrapper(null, fenxiao);
        BigDecimal noClean = fenxiaoService.getSumYongJin(fxWrapper);//未结算收益
        //查询用户的可提现金额
//        BigDecimal availablePredeposit = jmUser.getAvailablePredeposit();//可提现金额
        //替换为请求钱包接口获取可提现金额
        BigDecimal availablePredeposit = iWalletInOrOutService.waitCash(memberId.longValue());

        JmUserSales sales = new JmUserSales();
        sales.setUid(memberId);
        sales.setBuyerId(memberId);
        sales.setStatus(SalesStatus.正常);
        sales.setIsDel(CommonEnum.否);
        QueryWrapper salesWrapper = WrapperUtil.getWrapper(null, sales);
        BigDecimal selfMoney = salesService.getSelfMoney(salesWrapper);//自购省钱
        FenXiaoAggregate fenXiaoAggregate = new FenXiaoAggregate(sumYongJin, noClean, availablePredeposit, selfMoney);


        //查询今日收益--
        FenXiaoItem fenXiaoItemToday = getFenxiao(memberId, LocalDateTimeUtil.getMinTimeByDate(LocalDate.now()), null);


        //查看昨日收益--
        FenXiaoItem fenxiaoYesterday = packFenXiaoHistory(memberId, 1);
        //查看昨日收益

        //查看7天收益--
        FenXiaoItem fenxiaoSevenDay = packFenXiaoHistory(memberId, 2);
        //查看7天收益

        //查看30天收益--
        FenXiaoItem fenxiaoThirtyDay = packFenXiaoHistory(memberId, 3);
        //查看30天收益

        fenXiaoAggregate.setFenXiaoToday(fenXiaoItemToday);
        fenXiaoAggregate.setFenXiaoYesterday(fenxiaoYesterday);
        fenXiaoAggregate.setFenXiaoSevenDay(fenxiaoSevenDay);
        fenXiaoAggregate.setFenXiaoThirtyDay(fenxiaoThirtyDay);
        return ResponseResult.success(fenXiaoAggregate);
    }

    public FenXiaoItem packFenXiaoHistory(Integer memberId, int historyType) {
        FenXiaoItem fenXiaoItem = new FenXiaoItem();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uid", memberId);
        JmUserStatisticsTeam team = statisticsTeamService.getOne(wrapper);
        team = team == null ? new JmUserStatisticsTeam() : team;
        JmUserStatisticsFenxiao fenxiao = statisticsFenxiaoService.getOne(wrapper);
        fenxiao = fenxiao == null ? new JmUserStatisticsFenxiao() : fenxiao;
        JmUserStatisticsSales sales = statisticsSalesService.getOne(wrapper);
        sales = sales == null ? new JmUserStatisticsSales() : sales;
        switch (historyType) {
            case 1:
                fenXiaoItem = new FenXiaoItem(fenxiao.getFenxiaoYesterday(), fenxiao.getFenxiaoTgYesterday()
                        , fenxiao.getFenxiaoFwYesterday(), sales.getOrderCountYesterday(), sales.getSalesYesterday(), team.getTeamTgYesterday());
                break;
            case 2:
                fenXiaoItem = new FenXiaoItem(fenxiao.getFenxiaoWeek(), fenxiao.getFenxiaoTgWeek()
                        , fenxiao.getFenxiaoFwWeek(), sales.getOrderCountWeek(), sales.getSalesWeek(), team.getTeamTgWeek());
                break;
            case 3:
                fenXiaoItem = new FenXiaoItem(fenxiao.getFenxiaoMonth(), fenxiao.getFenxiaoTgMonth()
                        , fenxiao.getFenxiaoFwMonth(), sales.getOrderCountMonth(), sales.getSalesMonth(), team.getTeamTgMonth());
                break;
            default:
                break;
        }

        return fenXiaoItem;
    }

    @PostMapping("/getFenXiaoDetailByType")
    @ApiOperation(value = "用户收益明细", tags = "用户收益明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号"),
            @ApiImplicitParam(name = "time", value = "查询日期", example = "2020-05-11"),
            @ApiImplicitParam(name = "type", value = "收益类型"),
            @ApiImplicitParam(name = "status", value = "收益状态")
    })
    public Object getFenXiaoDetailByType(@ApiParam(value = "每页显示数量", required = true) @RequestParam Integer size,
                                         @ApiParam(value = "当前页", required = true) @RequestParam Integer current,
                                         String mobile,
                                         FenXiaoStatus status,
                                         FenXiaoType type,
                                         String time,
                                         @ApiParam(value = "查询日期类型;-1=所有,0=今日,1=昨日,7=7天,30=30天", required = true) @RequestParam byte sign) {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        userService.checkUserExist(memberId);

        JmUserFenxiao fenxiao = new JmUserFenxiao();
        fenxiao.setStatus(status);
        fenxiao.setType(type);
        fenxiao.setIsDel(CommonEnum.否);
        fenxiao.setUid(memberId);

        QueryWrapper wrapper = WrapperUtil.getWrapper(null, fenxiao);
        if (StrUtil.isNotEmpty(time) && sign == -1) {
            LocalDateTime minTimeByDate = LocalDateTimeUtil.getMinTimeByDate(LocalDate.parse(time));
            LocalDateTime maxTimeByDate = LocalDateTimeUtil.getMaxTimeByDate(LocalDate.parse(time));
            WrapperUtil.setTimeQueryWrapper(wrapper, minTimeByDate, maxTimeByDate);
        } else if (ArrayUtil.contains(new int[]{0, 1, 7, 30}, sign)) {
            LocalDateTime nBeforeMinTime = LocalDateTimeUtil.getNBeforeMinTime(sign);
            LocalDateTime nBeforeMaxTime = null;
            if (sign != 0) {
                nBeforeMaxTime = LocalDateTimeUtil.getNBeforeMaxTime(1);
            }
            WrapperUtil.setTimeQueryWrapper(wrapper, nBeforeMinTime, nBeforeMaxTime);
        }
        if (StrUtil.isNotEmpty(mobile)) {
            //验证当前登录用户，是否能查询此手机号
            JmUser userByMobile = userService.getUserByMobile(mobile);//查询用户
            if (ObjectUtil.isEmpty(userByMobile))
                return ResponseResult.error("手机号不存在!");
            QueryWrapper teamWrapper = new QueryWrapper();
            teamWrapper.eq("team_uid", memberId);
            teamWrapper.eq("uid", userByMobile.getId());
            teamWrapper.eq("is_del", 0);
            JmUserTeam userTeam = userTeamService.getOne(teamWrapper);
            if (ObjectUtil.isEmpty(userTeam)) {
                return ResponseResult.error("上级关系错误，不允许查询!");
            }
            wrapper.eq("buyer_id", userByMobile.getId());
        }
        Page page = new Page(current, size);
        wrapper.orderByDesc("id");
        page = fenxiaoService.getFenXiaoDetail(page, wrapper);

        Map<String, Object> map = new LinkedHashMap<>(2);
        BigDecimal sumYongJin = fenxiaoService.getSumYongJin(wrapper);

        map.put("page", page);
        map.put("sumYongJin", sumYongJin);
        return ResponseResult.success(map);
    }


    @PostMapping("/getSelfRecord")
    @ApiOperation(value = "自购省明细", tags = "自购省明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "查询日期", example = "2020-05-11"),
    })
    public ResponseResult getSelfRecord(String time,
                                        @ApiParam(value = "当前页", required = true) @RequestParam Integer current,
                                        @ApiParam(value = "显示数量", required = true) @RequestParam Integer size) {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        userService.checkUserExist(memberId);
        JmUserSales sales = new JmUserSales();
        sales.setUid(memberId);
        sales.setBuyerId(memberId);
        sales.setStatus(SalesStatus.正常);
        sales.setIsDel(CommonEnum.否);
        QueryWrapper wrapper = WrapperUtil.getWrapper(null, sales);
        if (StrUtil.isNotEmpty(time)) {
            LocalDateTime minTimeByDate = LocalDateTimeUtil.getMinTimeByDate(LocalDate.parse(time));
            LocalDateTime maxTimeByDate = LocalDateTimeUtil.getMaxTimeByDate(LocalDate.parse(time));
            WrapperUtil.setTimeQueryWrapper(wrapper, minTimeByDate, maxTimeByDate);
        }
        Page<SelfShopResponse> page = salesService.getSelfPage(new Page(current, size), wrapper);
        BigDecimal selfMoney = salesService.getSelfMoney(wrapper);
        /*List<SelfShopResponse> records = page.getRecords();
        for (SelfShopResponse record : records) {
            BigDecimal self = record.getSelfMoney();
            selfMoney = selfMoney.add(self);
        }*/

        Map map = new HashMap(2);
        map.put("page", page);
        map.put("selfMoney", selfMoney);
        return ResponseResult.success(map);
    }


    public FenXiaoItem getFenxiao(Integer memberId, LocalDateTime beginTime, LocalDateTime endTime) {

        JmUserFenxiao fenxiao = new JmUserFenxiao();//用来构建查询条件,查询用户总收益
        fenxiao.setUid(memberId);
        fenxiao.setIsDel(CommonEnum.否);
        QueryWrapper fxWrapper = WrapperUtil.getWrapper(null, fenxiao);
        fxWrapper.ne("status", FenXiaoStatus.失效);
        WrapperUtil.setTimeQueryWrapper(fxWrapper, beginTime, endTime);

        fxWrapper.groupBy("type");
        List<CommonGroup> sumYongJinByType = fenxiaoService.getSumYongJinByType(fxWrapper);

        BigDecimal tg = BigDecimal.ZERO;//推广收益
        BigDecimal fw = BigDecimal.ZERO;//服务收益

        for (CommonGroup commonGroup : sumYongJinByType) {
            Integer type = commonGroup.getType();
            BigDecimal price = commonGroup.getPrice();
            if (type.equals(FenXiaoType.推广收益.getValue())) {
                tg = tg.add(price);
            } else if (type.equals(FenXiaoType.服务收益.getValue())) {
                fw = fw.add(price);
            }
        }

        //构建sales查询条件,查询成交的订单数量 与 订单金额;
        JmUserSales sales = new JmUserSales();
        sales.setUid(memberId);
        sales.setStatus(SalesStatus.正常);
        sales.setIsDel(CommonEnum.否);
        QueryWrapper salesWrapper = WrapperUtil.getWrapper(null, sales);
        WrapperUtil.setTimeQueryWrapper(salesWrapper, beginTime, endTime);
        Integer sumOrderNum = salesService.getSumOrderNum(salesWrapper);//订单数量
        BigDecimal payPrice = salesService.getSumSales(salesWrapper);//成交金额

        //构建invite 的查询条件，查询今日邀请注册的人数
        JmUserInvite invite = new JmUserInvite();
        invite.setInviteUid(fenxiao.getUid());
        invite.setIsDel(fenxiao.getIsDel());
        QueryWrapper inviteWrapper = WrapperUtil.getWrapper(null, invite);
        WrapperUtil.setTimeQueryWrapper(inviteWrapper, beginTime, endTime);
        int inviterCount = inviteService.count(inviteWrapper);//邀请人数
        FenXiaoItem f = new FenXiaoItem(formatBigDecimal(tg.add(fw)), formatBigDecimal(tg), formatBigDecimal(fw), sumOrderNum, formatBigDecimal(payPrice), inviterCount);
        return f;
    }

    private BigDecimal formatBigDecimal(BigDecimal target) {
        return target.setScale(2, RoundingMode.DOWN);
    }

}
